package com.bshinfo.web.service.serviceImpl.site;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.bshinfo.web.base.model.Page;
import com.bshinfo.web.base.util.ConstantUtil;
import com.bshinfo.web.base.util.DateUtil;
import com.bshinfo.web.base.util.MapUtil;
import com.bshinfo.web.base.util.PaginationUtil;
import com.bshinfo.web.base.util.UUIDTool;
import com.bshinfo.web.dao.site.SiteManageMapper;
import com.bshinfo.web.model.dataTableUtil.DataTableModel;
import com.bshinfo.web.service.serviceI.site.SiteManageI;

@Service
public class SiteManageImpl implements SiteManageI
{
	@Resource
	private SiteManageMapper siteManageMapper;

	@Override
	public String selectAreaTree()
	{
		// 转成驼峰
		List<Map<String, Object>> areaList = MapUtil.convertDBReturnList(siteManageMapper.selectAllArea());
		// 江苏省节点的所有市节点列表
		JSONArray jaTwo = new JSONArray();
		JSONObject rootObject = new JSONObject();
		// 根节点Map
		Map<String, Object> rootArea = null;
		// 先找根节点江苏省
		for (Map<String, Object> area : areaList)
		{
			if (area.get("areaType").toString().trim().equals("1"))
			{
				rootArea = area;
				break;
			}
		}
		rootObject.put("id", rootArea.get("id"));
		rootObject.put("attributes", rootArea);
		rootObject.put("text", rootArea.get("areaName"));
		// 找根节点下面的子节点
		JSONObject item = new JSONObject();
		item.put("text", "江苏在线学习");
		jaTwo.add(item);
		// 找江苏省下面的所有的市-city 区-district
		for (Map<String, Object> city : areaList)
		{
			if (city.get("parentId").toString().trim().equals((rootArea.get("id").toString().trim())))
			{
				// 市JSON对象
				JSONObject jsonObjectArea = new JSONObject();
				jsonObjectArea.put("id", city.get("id"));
				jsonObjectArea.put("text", city.get("areaName"));
				jsonObjectArea.put("attributes", city);
				// 再一层循环获取该市下面所有的区
				JSONArray jaThree = new JSONArray();
				for (Map<String, Object> district : areaList)
				{
					if (district.get("parentId").toString().trim().equals(city.get("id").toString().trim()))
					{
						JSONObject cityMap = new JSONObject();
						cityMap.put("id", district.get("id"));
						cityMap.put("text", district.get("areaName"));
						cityMap.put("attributes", district);
						if(district.get("children").toString().equals("0"))
						{
							cityMap.put("icon","fa fa-file icon-state-warning icon-lg");
						}
						jaThree.add(cityMap);
					}
				}
				if (jaThree.size() != 0)
				{
					jsonObjectArea.put("children", jaThree);
				}
				jaTwo.add(jsonObjectArea);
			}
		}
		rootObject.put("children", jaTwo);
		return rootObject.toString();
	}

	@Override
	public DataTableModel selectAllSiteByCondition(Map<String, String> conditionMap)
	{
		Map<String, Object> paramMap = new HashMap<String, Object>();
		DataTableModel dataTableModel = new DataTableModel();
		List<List<Object>> data = new ArrayList<List<Object>>();

		// datatable表格插件传入的参数
		String sEcho = conditionMap.get("sEcho");
		int start = Integer.parseInt(conditionMap.get("iDisplayStart"));
		int length = Integer.parseInt(conditionMap.get("iDisplayLength"));
		int currentPage = start / length + 1;

		paramMap.put("searchAreaNodeId", conditionMap.get("searchAreaNodeId").trim());
		paramMap.put("searchSiteName", conditionMap.get("searchSiteName").trim());
		paramMap.put("searchSiteAbbr", conditionMap.get("searchSiteAbbr").trim());
		paramMap.put("searchSiteDomain", conditionMap.get("searchSiteDomain").trim());
		paramMap.put("searchSiteType", conditionMap.get("searchSiteType").trim());

		Page<Map<String, Object>> page = PaginationUtil.setPageInfoStart(paramMap, currentPage, length);

		// 从dao层获取list<map>数据
		List<Map<String, Object>> resList = MapUtil.convertDBReturnList(siteManageMapper.selectSiteListByConditionAndPage(page));
		Integer count = (int) siteManageMapper.countAllSiteByConditionMap(conditionMap);
		for (Map<String, Object> map : resList)
		{
			List<Object> rowList = new ArrayList<Object>();
			rowList.add(map.get("id"));
			rowList.add(map.get("siteName"));
			rowList.add(map.get("siteUrl"));
			rowList.add(JSON.toJSONString(map.get("districts")));// 覆盖区域
			rowList.add(map.get("siteType"));// 站点类型
			rowList.add(map.get("isEnabled"));
			rowList.add("");
			data.add(rowList);
		}
		dataTableModel.setiTotalDisplayRecords(count);
		dataTableModel.setiTotalRecords(count);
		dataTableModel.setsEcho(Integer.valueOf(sEcho));
		dataTableModel.setAaData(data);
		return dataTableModel;
	}

	public Object selecOneSiteInfo(String siteId)
	{
		return siteManageMapper.selecOneSiteInfo(siteId);
	}

	@Override
	public Boolean startSiteById(String siteId)
	{
		if (siteManageMapper.startSite(siteId) > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	@Override
	public Boolean pauseSiteById(String siteId)
	{
		if (siteManageMapper.pauseSite(siteId) > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	@Override
	public String virtualDeleteSiteById(String siteId)
	{
		// 看看有没有别的资源挂载在该站点下
		if (siteManageMapper.countUsersBySite(siteId) > 0)
		{
			return "当前站点存在用户!";
		}
		siteManageMapper.deleteSite(siteId);
		return "deleteSitetDone";
	}

	@SuppressWarnings("all")
	@Override
	public Boolean addNewSite(String info, String isAll, String cityId, String listArea)
	{
		Map siteInfo = json2Map(info);
		if (siteInfo.get("siteType").toString().trim().equals("3"))
		{
			// 存联盟网站
			siteInfo.put("id", UUIDTool.randomUUID());
			siteInfo.put("isEnabled", 1);
			siteInfo.put("createUserId", ConstantUtil.ADMIN_ID);
			siteInfo.put("createTime", DateUtil.getDateString(""));
			siteInfo.put("updateTime", DateUtil.getDateString(""));
			siteInfo.put("isDel", 0);
			siteManageMapper.addNewSite(siteInfo);
		}
		else if (siteInfo.get("siteType").toString().trim().equals("2"))
		{
			// 存子站
			if (siteInfo.get("siteUrl").toString().trim().equals("-1"))
			{
				// 网站需要系统生成
				siteInfo.put("siteUrl", "系统生成");
			}
			siteInfo.put("id", UUIDTool.randomUUID());
			siteInfo.put("createUserId", ConstantUtil.ADMIN_ID);
			siteInfo.put("createTime", DateUtil.getDateString(""));
			siteInfo.put("updateTime", DateUtil.getDateString(""));
			siteInfo.put("isDel", 0);
			siteManageMapper.addNewSite(siteInfo);
		}

		// 添加覆盖区域表
		if (isAll.equals("yes"))
		{
			Map<String, Object> siteArea = new HashMap<String, Object>();
			siteArea.put("siteId", siteInfo.get("id"));
			siteArea.put("areaId", cityId);
			siteArea.put("createUserId", ConstantUtil.ADMIN_ID);
			siteArea.put("createTime", DateUtil.getDateString(""));
			siteArea.put("updateTime", DateUtil.getDateString(""));
			siteManageMapper.addNewSiteArea(siteArea);
		}
		else
		{
			JSONArray ja = JSONArray.fromObject(listArea);
			for (int i = 0; i < ja.size(); i++)
			{
				Map<String, Object> siteArea = new HashMap<String, Object>();
				siteArea.put("siteId", siteInfo.get("id"));
				siteArea.put("areaId", ja.get(i).toString());
				siteArea.put("createUserId", ConstantUtil.ADMIN_ID);
				siteArea.put("createTime", DateUtil.getDateString(""));
				siteArea.put("updateTime", DateUtil.getDateString(""));
				siteManageMapper.addNewSiteArea(siteArea);
			}
		}
		return true;
	}

	/**
	 * 编辑站点
	 */
	@SuppressWarnings("all")
	@Override
	public Boolean modifySiteInfoByInfo(String info, Boolean isCoverAreaModify, String isAll, String cityId, String listArea)
	{
		// 首先修改站点基础信息
		Map siteInfo = json2Map(info);
		siteInfo.put("updateTime", DateUtil.getDateString(""));
		siteManageMapper.modifySiteInfoByInfo(siteInfo);

		// 是否编辑过覆盖区域
		if (isCoverAreaModify)
		{
			// 删除该站点所有的覆盖区域
			siteManageMapper.deleteAllAreaBySite(siteInfo.get("siteId").toString());
			if (isAll.equals("yes"))
			{
				Map<String, Object> siteArea = new HashMap<String, Object>();
				siteArea.put("siteId", siteInfo.get("siteId"));
				siteArea.put("areaId", cityId);
				siteArea.put("createUserId", ConstantUtil.ADMIN_ID);
				siteArea.put("createTime", DateUtil.getDateString(""));
				siteArea.put("updateTime", DateUtil.getDateString(""));
				siteManageMapper.addNewSiteArea(siteArea);
			}
			else
			{
				// 新增所有的覆盖区域
				JSONArray ja = JSONArray.fromObject(listArea);
				for (int i = 0; i < ja.size(); i++)
				{
					Map<String, Object> siteArea = new HashMap<String, Object>();
					siteArea.put("siteId", siteInfo.get("siteId"));
					siteArea.put("areaId", ja.get(i).toString());
					siteArea.put("createUserId", ConstantUtil.ADMIN_ID);
					siteArea.put("createTime", DateUtil.getDateString(""));
					siteArea.put("updateTime", DateUtil.getDateString(""));
					siteManageMapper.addNewSiteArea(siteArea);
				}
			}

		}
		else
		{
			return true;
		}
		return true;
	}

	/**
	 * 将JSON转为Map 仅支持1级
	 * 
	 * @param jsonString
	 * @return
	 */
	public static Map<String, String> json2Map(String jsonString)
	{
		net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(jsonString);
		Map<String, String> map = new HashMap<String, String>();
		for (Iterator<?> iter = jsonObject.keys(); iter.hasNext();)
		{
			String key = (String) iter.next();
			map.put(key, String.valueOf(jsonObject.get(key)));
		}
		return map;
	}

}
